# -*- coding: utf-8 -*-

from conf.entity.module.git_config import GitProject, GiteeConfig, GitBranchPair
import requests
import json


class GiteeOperation:
    gitee_config: GiteeConfig
    project: GitProject

    def __init__(self, gitee_config: GiteeConfig, project: GitProject):
        self.gitee_config = gitee_config
        self.project = project

    def do_pull_request_if_need(self, branch_pair: GitBranchPair):
        """
        only create PullRequest from upBranch to downBranch
        """
        if self.gitee_config is None or not self.gitee_config.do_pull:
            return
        if self.project.branches_no_diff or self.project.has_conflict:
            return

        owner = self.gitee_config.owner
        repo = self.project.gitee_path
        pr_url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/pulls'

        headers = {
            "content-type": "application/json",
            "charset": "UTF-8"
        }

        post_data = {
            'access_token': self.gitee_config.access_token,
            'title': self.gitee_config.pull_request_title,
            'head': branch_pair.down_branch,
            'base': branch_pair.up_branch
        }
        json_data = json.dumps(post_data)

        print(f'try to create PullRequest for project: {self.project.name}')
        res = requests.post(pr_url, data=json_data, headers=headers)

        if res.status_code == 200 or res.status_code == 201:
            self.project.pr_created = True
            print(f'PullRequest created successfully for project: {self.project.name}')
        else:
            print(f'pull request url: {pr_url}')
            print(f'failed to create PullRequest, status_code: {res.status_code}, reason: {res.reason}')
